<?php

namespace app\models;

use app\components\BaseActiveRecord;
use Yii;

/**
 * This is the model class for table "{{%group_user}}".
 *
 * @property int $id
 * @property string $group_num
 * @property string $phone
 * @property int $group_priority
 * @property int $role
 * @property int $create_time
 */
class GroupUser extends BaseActiveRecord {

    public $pageSize = 10;

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%group_user}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['group_num', 'phone'], 'required'],
            [['group_priority', 'role', 'create_time'], 'integer'],
            [['group_num', 'phone'], 'string', 'max' => 20],
            ['phone', 'validatePhone'],
        ];
    }

    public function validatePhone() {
        if (empty($this->phone) || !User::findOne(['phone' => $this->phone])) {
            $this->addError('phone', '电话号码不存在.');
        }
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'group_num' => '组号',
            'phone' => '电话号码',
            'group_priority' => '组成员优先级',
            'role' => '角色',
            'create_time' => '创建时间',
        ];
    }

    public function afterSave($insert, $changedAttributes) {
        parent::afterSave($insert, $changedAttributes);
        if ($this->isGenerateFile) {
            Group::generateFiles(Group::findOne(['group_num' => $this->group_num]));
            User::generateFiles(User::findOne(['phone' => $this->phone]), FALSE);
        }
    }
}
